import { createServer } from 'http';

const PORT = process.env.PORT || 3000;

const server = createServer(async (req, res) => {
  const url = new URL(req.url || '/', `http://${req.headers.host}`);
  
  // 设置CORS头
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  // 设置JSON响应头
  res.setHeader('Content-Type', 'application/json; charset=utf-8');

  try {
    switch (req.method) {
      case 'GET':
        if (url.pathname === '/') {
          res.writeHead(200);
          res.end(JSON.stringify({
            message: '欢迎使用 TSX HTTP 应用！',
            timestamp: new Date().toISOString(),
            endpoints: {
              'GET /': '欢迎信息',
              'GET /time': '当前服务器时间',
              'POST /echo': '回显收到的JSON数据'
            }
          }, null, 2));
        } else if (url.pathname === '/time') {
          res.writeHead(200);
          res.end(JSON.stringify({
            currentTime: new Date().toISOString(),
            timestamp: Date.now(),
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
          }, null, 2));
        } else {
          res.writeHead(404);
          res.end(JSON.stringify({ error: '未找到接口' }));
        }
        break;

      case 'POST':
        if (url.pathname === '/echo') {
          let body = '';
          req.on('data', chunk => {
            body += chunk.toString();
          });
          
          req.on('end', () => {
            try {
              const data = body ? JSON.parse(body) : {};
              res.writeHead(200);
              res.end(JSON.stringify({
                received: data,
                timestamp: new Date().toISOString(),
                method: 'POST',
                url: req.url
              }, null, 2));
            } catch (error) {
              res.writeHead(400);
              res.end(JSON.stringify({ error: '无效的JSON格式' }));
            }
          });
        } else {
          res.writeHead(404);
          res.end(JSON.stringify({ error: '未找到接口' }));
        }
        break;

      default:
        res.writeHead(405);
        res.end(JSON.stringify({ error: '不支持的HTTP方法' }));
    }
  } catch (error) {
    res.writeHead(500);
    res.end(JSON.stringify({ error: '服务器内部错误' }));
  }
});

server.listen(PORT, () => {
  console.log(`🚀 TSX HTTP 服务器运行在 http://localhost:${PORT}`);
  console.log('📋 可用接口:');
  console.log('   GET  /      - 欢迎信息');
  console.log('   GET  /time  - 当前时间');
  console.log('   POST /echo  - JSON回显');
});
